/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejercicio.practica6;

import java.util.Random;
import java.util.Scanner;

/**
 *
 * @author manolo
 */
public class suavImagenParGru implements Runnable {

    private static int[][] imagen;
    private  int limSup, limInf;
    private static int fil, col, m;

    public suavImagenParGru(int limInf, int limSup) {
       this.limSup = limSup;
       this.limInf = limInf;
    }

    private static void inicializarImagen(int m) {
        Random rm = new Random();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < m; j++) {
                imagen[i][j] = rm.nextInt(20);
            }
        }
    }

    @Override
    public void run() {
        for (int i = limInf; i < limSup; i++) {
            fil = (i / (m-2)) + 1;
            col = (i % (m - 2) + 1);
            imagen[fil][col] = (4 * imagen[fil][col] - imagen[fil + 1][col] - imagen[fil][col + 1] - imagen[fil - 1][col] - imagen[fil][col - 1]) / 8;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        long inicio, fin;
        int tVentana;
        Scanner teclado = new Scanner(System.in);
        int nTareas = Runtime.getRuntime().availableProcessors();

        System.out.println("Introduzca la dimension de la imagen: ");
        m = teclado.nextInt();
        imagen = new int[m][m];
        int nPuntos = (m - 2) * (m - 2);
        tVentana = nPuntos / nTareas;
        int linf = 0;
        int lsup = tVentana;
        inicializarImagen(m);
        inicio = System.currentTimeMillis();
        Thread[] Hilos = new Thread[nTareas];
        for (int i = 0; i < nTareas; ++i) {
            Hilos[i] = new Thread(new suavImagenParGru(linf, lsup));
            Hilos[i].start();   Hilos[i].join();
            linf = lsup;
            lsup += tVentana;
        }
        for (int i = 0; i < nTareas; ++i) {
            Hilos[i].join();
        }
        fin = System.currentTimeMillis();
        System.out.println("Se ha invertido " + (fin - inicio) + " mseg.");

    }

}
